import React, { PureComponent } from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Row, Col, Select, Input, Cascader, Button, message, Spin } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import DictCode from '../../components/DictCode';
import FooterToolbar from '@/components/FooterToolbar';
import HOCSelect from '@/components/AntDesign/Select';

const { Option } = Select;
const FormItem = Form.Item;
@connect(({ usermanage, loading, login }) => ({
  usermanage,
  login,
  loading: loading.models.usermanage,
  searchLoading: loading.effects['usermanage/fetchCustList'],
}))
@Form.create()
class BasicList extends PureComponent {
  state = {};

  async componentDidMount() {
    const {
      dispatch,
      location: { pathname, query },
    } = this.props;
    const { userId, userType } = query;
    const action = pathname.indexOf('add') > -1 ? 'add' : 'update';

    // 新增页面
    await dispatch({
      type: 'usermanage/updateModalData',
      payload: {
        action,
      },
    });
    // 岗位
    await dispatch({
      type: 'usermanage/fetchDictList',
      payload: ['POST_TYPE'],
    });
    // 公司
    await dispatch({
      type: 'usermanage/fetchOrgInfo',
      payload: {},
    });
    // 角色
    await dispatch({
      type: 'usermanage/fetchBaseRoleLike',
      payload: { roleType: action === 'add' ? '3' : userType },
    });
    if (action === 'add') {
      await dispatch({
        type: 'usermanage/updateModalData',
        payload: {
          updateInfo: {},
        },
      });
    } else {
      // 详情
      await dispatch({
        type: 'usermanage/fetchUserInfoById',
        payload: { userId },
      });
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'usermanage/updateModalData',
      payload: {
        assoUserFlag: null,
        assoCustsFlag: null,
      },
    });
  }

  loadAreaData = selectedOptions => {
    const {
      dispatch,
      usermanage: { provCityAreaList },
    } = this.props;
    const corpId = selectedOptions[selectedOptions.length - 1].value;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    targetOption.children = [];
    dispatch({
      type: 'usermanage/fetchOrgListByParentId',
      payload: {
        type: 2,
        orgId: corpId,
        isChild: true,
      },
    }).then(resData => {
      setTimeout(() => {
        targetOption.loading = false;
        targetOption.children = resData;
        dispatch({
          type: 'usermanage/updateModalData',
          payload: {
            provCityAreaList: [...provCityAreaList],
          },
        });
      }, 1000);
    });
  };

  // 所属公司
  corpIdChange = (value, key) => {
    const {
      dispatch,
      usermanage: { updateInfo },
    } = this.props;
    // 公司id
    const corpId = key.value;
    dispatch({
      type: 'usermanage/fetchOrgListByParentId',
      payload: {
        type: 1,
        corpId,
      },
    });
    dispatch({
      type: 'usermanage/updateModalData',
      payload: {
        updateInfo: {
          ...updateInfo,
          corpId: key.props.value, // 公司id
          corpName: key.props.children,
        },
      },
    });
  };

  // 公司
  selectProvCityArea = value => {
    const {
      dispatch,
      usermanage: { action, updateInfo },
    } = this.props;
    const { postTypeValue } = this.state;
    dispatch({
      type: 'usermanage/updateModalData',
      payload: {
        updateInfo: {
          ...updateInfo,
          orgId: value[value.length - 1], // 机构id
        },
      },
    });
    this.onSelectedDom(postTypeValue, updateInfo.corpId, value[value.length - 1], action);
  };

  // 获取地址
  searchCust = value => {
    const {
      dispatch,
      usermanage: { updateInfo },
    } = this.props;
    if (value.trim().length) {
      dispatch({
        type: 'usermanage/fetchCustList',
        payload: { name: value.trim(), corpId: updateInfo.corpId },
      });
    }
  };

  // 选择岗位
  onChangePostType = value => {
    const {
      usermanage: { updateInfo, action },
    } = this.props;
    this.onSelectedDom(Number(value), updateInfo.corpId, updateInfo.orgId, action);
  };

  onSelectedDom = (value, corpId, orgId, action) => {
    const {
      dispatch,
      form,
      location: { query },
    } = this.props;
    this.setState({ postTypeValue: value });
    const { userType } = query;
    // 助理岗
    if (value === 3) {
      if (corpId && orgId) {
        // 根据公司id 查所属用户
        dispatch({
          type: 'usermanage/fetchQueryUserByOrgId',
          payload: { corpId, orgId, userType: 3, postTypes: [1, 2, 4] },
        });
        dispatch({
          type: 'usermanage/updateModalData',
          payload: { roleList: [], assoUserFlag: true, assoCustsFlag: false },
        });
        dispatch({
          type: 'usermanage/updateModalClearFrom',
          payload: {
            assoUser: undefined,
            assoCusts: undefined,
            roles: [],
          },
        });
        form.resetFields(['assoUser', 'assoCusts', 'roles']);
      } else {
        message.warning('您所选的岗位是助理岗，请先选择公司和所属部门');
      }
    }
    // onSite
    if (value === 4) {
      dispatch({
        type: 'usermanage/fetchBaseRoleLike',
        payload: { roleType: 3, sysIds: ['BS0000000003', 'BS0000000001'] },
      });
      dispatch({
        type: 'usermanage/updateModalData',
        payload: { assoCustsFlag: true, assoUserFlag: false, custList: [] },
      });
      dispatch({
        type: 'usermanage/updateModalClearFrom',
        payload: {
          assoUser: undefined,
          assoCusts: undefined,
          roles: [],
        },
      });
      form.resetFields(['assoUser', 'assoCusts', 'roles']);
    }
    if (value !== 3 && value !== 4) {
      dispatch({
        type: 'usermanage/updateModalData',
        payload: { assoCustsFlag: false, assoUserFlag: false },
      });
      dispatch({
        type: 'usermanage/updateModalClearFrom',
        payload: {
          roles: [],
        },
      });
      dispatch({
        type: 'usermanage/fetchBaseRoleLike',
        payload: { roleType: action === 'add' ? '3' : userType },
      });
      form.resetFields(['assoUser', 'assoCusts', 'roles']);
    }
  };

  // 所选用户
  onChangeAssoUser = value => {
    // 该用户下的角色
    const { dispatch, form } = this.props;
    dispatch({
      type: 'usermanage/fetchUserInfoById',
      payload: { userId: value, add: '1' },
    });
    dispatch({
      type: 'usermanage/updateModalClearFrom',
      payload: {
        roles: [],
      },
    });
    form.resetFields(['roles']);
  };

  cancel = () => {
    router.goBack();
  };

  // 验证新增提交
  submitAdd = e => {
    e.preventDefault();
    const { form, dispatch } = this.props;

    form.validateFieldsAndScroll((err, fieldValues) => {
      if (!err) {
        const tempFieldsValue = {};
        Object.keys(fieldValues).forEach(key => {
          if (key === 'roles') {
            tempFieldsValue[key] = fieldValues[key].map(keyItem => ({
              roleId: keyItem,
            }));
          } else if (key === 'orgId') {
            tempFieldsValue[key] = fieldValues[key][fieldValues[key].length - 1];
          } else {
            tempFieldsValue[key] = fieldValues[key];
          }
        });
        dispatch({
          type: 'usermanage/addUserInfo',
          payload: { ...tempFieldsValue, userStatus: 1 },
        });
      }
    });
  };

  // 验证修改提交
  submitUpdate = e => {
    e.preventDefault();
    const {
      form,
      dispatch,
      usermanage: { updateInfo },
    } = this.props;
    form.validateFieldsAndScroll((err, fieldValues) => {
      if (!err) {
        const tempFieldsValue = {};
        Object.keys(fieldValues).forEach(key => {
          if (key === 'roles') {
            tempFieldsValue[key] = fieldValues[key].map(keyItem => ({
              roleId: keyItem,
            }));
          } else if (key === 'orgId') {
            tempFieldsValue[key] = updateInfo.orgId;
          } else if (key === 'userPwd') {
            tempFieldsValue[key] = undefined;
          } else {
            tempFieldsValue[key] = fieldValues[key];
          }
        });
        dispatch({
          type: 'usermanage/updateUserInfo',
          payload: { ...tempFieldsValue, userId: updateInfo.userId },
        });
      }
    });
  };

  render() {
    const {
      form: { getFieldDecorator },
      usermanage: {
        corpIdList,
        provCityAreaList,
        roleList,
        action,
        updateInfo,
        queryUserList,
        assoCustsFlag,
        assoUserFlag,
        custList,
      },
      searchLoading,
    } = this.props;
    // 权限管理  新增 表单 表单域配置
    const formItemLayout = {
      labelCol: { md: { span: 4 } },
      wrapperCol: { md: { span: 20 } },
    };

    const roleOption = roleList.map(options => (
      <Option key={options.roleId}>{options.roleName}</Option>
    ));
    const corpIdOption = corpIdList.map(options => (
      <Option key={options.orgId} value={options.corpId}>
        {options.name}
      </Option>
    ));
    const queryUserOption = queryUserList.map(options => (
      <Option key={options.userId}>{options.userName}</Option>
    ));
    const custOption = custList.map(options => (
      <Option key={options.custId}>{options.groupName}</Option>
    ));

    return (
      <PageHeaderWrapper>
        <Card title={<span>{action === 'add' ? '添加用户' : '修改用户'}</span>}>
          <Form>
            <Row>
              <Col span={24}>
                <FormItem label="姓名" {...formItemLayout}>
                  {getFieldDecorator('userName', {
                    rules: [
                      {
                        required: true,
                        message: '请填写姓名!',
                      },
                    ],
                    initialValue: updateInfo.userName,
                  })(<Input placeholder="请输入" style={{ width: '40%' }} />)}
                  <span style={{ marginLeft: 5, color: '#999' }}>
                    注：姓名含多音字时，请手动输入用户登录名和密码
                  </span>
                </FormItem>
                <FormItem label="身份证号" {...formItemLayout}>
                  {getFieldDecorator('userIdCard', {
                    rules: [
                      {
                        required: true,
                        message: '请输入合法的身份证号（15位或者18位）',
                        pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/,
                      },
                    ],
                    initialValue: updateInfo.userIdCard,
                  })(<Input placeholder="请输入" style={{ width: '40%' }} />)}
                </FormItem>
                <FormItem label="手机号" {...formItemLayout}>
                  {getFieldDecorator('mobile', {
                    rules: [
                      {
                        required: true,
                        message: '请输入11位手机号',
                        pattern: /^1[345789]\d{9}$/,
                      },
                    ],
                    initialValue: updateInfo.mobile,
                  })(<Input placeholder="请输入" style={{ width: '40%' }} />)}
                </FormItem>
                <FormItem label="邮箱" {...formItemLayout}>
                  {getFieldDecorator('email', {
                    rules: [
                      {
                        type: 'email',
                        message: '请输入你正确的邮箱!',
                      },
                      {
                        required: true,
                        message: '请输入你正确的邮箱！',
                      },
                    ],
                    initialValue: updateInfo.email,
                  })(<Input placeholder="请输入" style={{ width: '40%' }} />)}
                </FormItem>
                <FormItem label={<span>用户登录名</span>} {...formItemLayout}>
                  {getFieldDecorator('loginName', {
                    rules: [
                      {
                        required: false,
                        message: '请输入你的用户登录名',
                      },
                    ],
                    initialValue: updateInfo.loginName,
                  })(
                    <Input
                      placeholder="请输入"
                      disabled={action === 'update'}
                      style={{ width: '40%' }}
                    />
                  )}
                  <span style={{ color: '#999' }}>
                    注：如未输入，用户登录名默认姓名拼音，如姓名重复，请手动输入用户登录名
                  </span>
                </FormItem>

                <FormItem label={<span>密码</span>} {...formItemLayout}>
                  {getFieldDecorator('userPwd', {
                    rules: [
                      {
                        required: false,
                        message: '6~16位英文字母、数字、字符组合。',
                        min: 6,
                        max: 16,
                      },
                    ],
                    initialValue: action === 'add' ? undefined : '********', // 后台没有返回"密码"字段,所以密码写死固定值
                  })(
                    <Input
                      type="password"
                      placeholder="请输入"
                      autoComplete="new-password"
                      style={{ width: '40%' }}
                      disabled={action === 'update'}
                    />
                  )}
                  <span style={{ color: '#999' }}> 注：如未输入，密码默认姓名拼音+123</span>
                </FormItem>

                <FormItem label="所属公司:" {...formItemLayout}>
                  {getFieldDecorator('corpId', {
                    rules: [
                      {
                        required: true,
                        message: '请选择所属公司!',
                      },
                    ],
                    initialValue: updateInfo.corpId,
                  })(
                    <HOCSelect
                      allowClear
                      showSearch
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                      placeholder="请选择"
                      onSelect={this.corpIdChange}
                      style={{ width: '40%' }}
                      disabled={action === 'update'}
                    >
                      {corpIdOption}
                    </HOCSelect>
                  )}
                </FormItem>
                {action === 'add' ? (
                  <FormItem label="所属部门:" {...formItemLayout}>
                    {getFieldDecorator('orgId', {
                      rules: [
                        {
                          required: true,
                          message: '请选择所属部门!',
                        },
                      ],
                      initialValue: [],
                    })(
                      <Cascader
                        allowClear
                        showSearch
                        filterOption={(input, option) =>
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        placeholder="请选择所属部门"
                        options={provCityAreaList}
                        loadData={this.loadAreaData}
                        onChange={this.selectProvCityArea}
                        changeOnSelect
                        style={{ width: '40%' }}
                      />
                    )}
                  </FormItem>
                ) : (
                  <FormItem label="所属部门:" {...formItemLayout}>
                    {getFieldDecorator('orgId', {
                      rules: [
                        {
                          required: true,
                          message: '请选择所属部门!',
                        },
                      ],
                      initialValue: updateInfo.orgIdName,
                    })(<Input disabled={action === 'update'} style={{ width: '40%' }} />)}
                  </FormItem>
                )}
                <FormItem label="岗位" {...formItemLayout}>
                  {getFieldDecorator('postType', {
                    rules: [
                      {
                        required: true,
                        message: '请选择岗位',
                      },
                    ],
                    initialValue: updateInfo.postType,
                  })(
                    <DictCode
                      allowClear
                      showSearch
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                      dictType="POST_TYPE"
                      style={{ width: '40%' }}
                      onChange={this.onChangePostType}
                    />
                  )}
                </FormItem>
                {assoUserFlag && (
                  <FormItem label="所属用户" {...formItemLayout}>
                    {getFieldDecorator('assoUser', {
                      rules: [
                        {
                          required: true,
                          message: '请选择所属用户',
                        },
                      ],
                      initialValue: updateInfo.assoUser,
                    })(
                      <HOCSelect
                        showSearch
                        placeholder="请选择所属用户"
                        style={{ width: '40%' }}
                        optionFilterProp="children"
                        onChange={this.onChangeAssoUser}
                        filterOption={(input, option) =>
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                      >
                        {queryUserOption}
                      </HOCSelect>
                    )}
                  </FormItem>
                )}

                {assoCustsFlag && (
                  <FormItem label="关联客户" {...formItemLayout}>
                    {getFieldDecorator('assoCusts', {
                      rules: [
                        {
                          required: true,
                          message: '请选择关联客户',
                        },
                      ],
                      initialValue: updateInfo.assoCusts,
                    })(
                      <HOCSelect
                        showSearch
                        placeholder="请选择关联客户"
                        style={{ width: '40%' }}
                        optionFilterProp="children"
                        mode="multiple"
                        filterOption={(input, option) =>
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        onSearch={this.searchCust}
                        notFoundContent={searchLoading ? <Spin size="small" /> : null}
                      >
                        {custOption}
                      </HOCSelect>
                    )}
                  </FormItem>
                )}

                <FormItem label="角色:" {...formItemLayout}>
                  {getFieldDecorator('roles', {
                    rules: [
                      {
                        required: true,
                        message: '请选择角色!',
                      },
                    ],
                    initialValue: updateInfo.roles,
                  })(
                    <HOCSelect
                      showSearch
                      placeholder="请选择/经理/主管/运行专员/..."
                      style={{ width: '40%' }}
                      optionFilterProp="children"
                      mode="multiple"
                      filterOption={(input, option) =>
                        option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                      }
                    >
                      {roleOption}
                    </HOCSelect>
                  )}
                </FormItem>
                <FormItem label="备注" {...formItemLayout}>
                  {getFieldDecorator('remark', {
                    rules: [
                      {
                        required: false,
                        message: '请输入备注!',
                      },
                    ],
                    initialValue: updateInfo.remark,
                  })(<Input placeholder="请输入" style={{ width: '40%' }} />)}
                </FormItem>
              </Col>
            </Row>
          </Form>
          <FooterToolbar>
            <Button onClick={this.cancel} style={{ marginRight: 10 }}>
              {' 取消 '}
            </Button>
            <Button type="primary" onClick={action === 'add' ? this.submitAdd : this.submitUpdate}>
              提交
            </Button>
          </FooterToolbar>
        </Card>
      </PageHeaderWrapper>
    );
  }
}

const BasicListFrom = Form.create()(BasicList);
export default BasicListFrom;
